package dexter.util;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.util.logging.Level;
import java.util.logging.Logger;


public class PublicIp {

	public static String getPublicIp() {
		
	     try {
	    
	    	URL url = new URL(null, "http://checkip.dyndns.org/");
	    	URLConnection connection = url.openConnection();
	    	connection.setReadTimeout(5000);
	    	Object content = connection.getContent();
	    	
	    	if (content!=null) {
	        BufferedReader in = new BufferedReader(new InputStreamReader((InputStream) content));
	        
	        char[] data = new char[10000]; // The characters read.
	        int index;
	        for(index=0;index<1000;index++) { // Read up to 10000 chars and store them in the array.
	            int ch = in.read();
	            if (ch == -1) break;
	            data[index] = (char)ch;
	         }
	        String web=new String(data,0,index);
	        int inici=web.indexOf("<body>");
	        inici+=26;
	        int end=web.lastIndexOf("</body>");
	        in.close();
	        return new String(data,inici,end-inici); 
	    	}
	    } catch (IOException ex) {
	        Logger.getLogger(PublicIp.class.getName()).log(Level.SEVERE, null, ex);
	    }
	    return "";
	}
	
	
	public static void main(String[] args) {
		System.out.println("Public IP : "+getPublicIp());
	}

}